package core;

import model.*;
import util.MyList;

import java.util.Scanner;

/**
 * kaixin store
 */
public class Store {

    //管理员列表
    private static MyList adminList;
    //会员列表
    private static MyList vipList;
    //商品列表
    private static MyList goodslist;
    //商品分类
    private static MyList categoryList;

    /**
     * 会员等级
     */
    private static MyList levelList;

    /**
     * 当前登录用户
     */
    private Account currentUser;

    static {
        vipList = new MyList(3);
        adminList = new MyList(1);
        goodslist = new MyList(5);
        categoryList = new MyList(3);
        levelList = new MyList(5);
    }


    /**
     * Scanner对象
     */
    private static final Scanner INPUT = new Scanner(System.in);

    public Store(){
        //模拟已有管理员
        Admin admin = new Admin("12345","11","慢羊羊村长");
        adminList.add(admin);

        levelList.add(new Level("普通会员", 0, 1));
        levelList.add(new Level("黄金会员", 100, 0.9));
        levelList.add(new Level("铂金会员", 300, 0.85));
        levelList.add(new Level("钻石会员", 1000, 0.75));
        levelList.add(new Level("黑金会员", 5000, 0.7));

        //模拟已有会员
        Vip vip1 = new Vip("123","123","懒羊羊",(Level) levelList.getElement(0));
        vipList.add(vip1);
        Vip vip2 = new Vip("234","234","喜羊羊",(Level) levelList.getElement(0));
        vipList.add(vip2);
        Vip vip3 = new Vip("345","345","美羊羊",(Level) levelList.getElement(0));
        vipList.add(vip3);
        Vip vip4 = new Vip("456","456","沸羊羊",(Level) levelList.getElement(0));
        vipList.add(vip4);
        Vip vip5 = new Vip("567","567","灰太狼",(Level) levelList.getElement(0));
        vipList.add(vip5);
        //模拟已有商品分类
        categoryList.add(new Category(1,"蛋糕"));
        categoryList.add(new Category(2,"果汁"));
        categoryList.add(new Category(3,"羊肉"));
        //模拟已有商品
        Goods goods1 = new Goods("001","青草蛋糕",3.2,5.8,20,(Category) categoryList.getElement(0));
        goodslist.add(goods1);
        goodslist.add(new Goods("002","青草汁",1.8,4,4000,(Category) categoryList.getElement(1)));
        goodslist.add(new Goods("003","草莓汁",3.2,5,400,(Category) categoryList.getElement(1)));
        goodslist.add(new Goods("004","榴莲蛋糕",10,16,1000,(Category) categoryList.getElement(0)));
        goodslist.add(new Goods("005","炭烤小绵羊",60,100,2000,(Category) categoryList.getElement(2)));
        goodslist.add(new Goods("006","羊肉串",3,5,500,(Category) categoryList.getElement(2)));
        goodslist.add(new Goods("007","草莓蛋糕",5,10,200,(Category) categoryList.getElement(0)));







    }
    /**
     * 定义一个public方法，实现在main方法中调用非本类的私有类
     */
    public void open(){
        welcome();
        indexMenuList();
    }



    /**
    * 打印欢迎语
    */
    private void welcome(){
        println("*********************************************************");
        println("*                                                       *");
        println("*               Hi! 欢迎光临 开心小店                      *");
        println("*                                                       *");
        println("*********************************************************");
        println("  (客官你好，茶小乖在此提醒您，根据提示输入相应的编号才可以使用本系统奥！)");
    }
    /**
     * 首页功能提示
     */
    private void indexMenuList(){
        println("1————> 登录");
        println("2————> 注册");
        println("3————> 管理员登录");
        println("0————> 退出");
        print("请选择 ：");
        int in = INPUT.nextInt();
        router(in);
    }

    /**
     * 功能跳转
     */
    private void router(int in){
        switch (in){
            case 1 -> login();
            case 2 -> register();
            case 3 -> loginAdmin();
            case 201 -> showVipList();
            case 202 -> addGoods();
            case 203 -> isAddCategory();
            case 204 -> showCategory();

            case 205 -> {
                showGoodsList();
                adminMenuList();
            }
            case 0 -> exit();
            default -> {
                print("客官，指令不对奥，再输一遍：");
                router(INPUT.nextInt() );
            }
        }
    }
    private void isAddCategory(){
        showCategory();

        print("是否要添加新的商品分类？" + "\n" + " “1” 添加，“0” 不添加");
        do {
            int a = INPUT.nextInt();
            if (a == 0) {
                adminMenuList();
                break;
            }else if (a == 1){
                addCategory();
                break;
            }else {
                println( " 输入不规范，“1” 添加，“0” 不添加");
                print("请按指示输入:");
            }

        }while (true);



    }

    /**
     * 展示商品列表
     */
    private void showGoodsList() {
        println("商品列表如下：");
        if (currentUser instanceof Vip) {
            for (int i = 0; i < goodslist.size(); i++) {
                Goods element = (Goods) goodslist.getElement(i);
                if (element.getCount() > 0) {
                    println(element.show( ));
                }
            }
        }else {
            println(goodslist.toString());
        }
    }

    /**
     * 新增商品分类
     */
    private void addCategory() {
        showCategory();
        print("请输入分类编号：" );
        int no = INPUT.nextInt();
//        if (no == -1){        //+ "(提示：返回上级菜单，请输入 ：-1)
//            adminMenuList();
//        }

        println("请输入分类名称：");


        String name = INPUT.next();
        Category category = new Category(no,name);
        categoryList.add(category);
        adminMenuList();

    }

    /**
     * 商品入库
     */
    private void addGoods() {
        print("请输入商品编号：");
        String no = INPUT.next();
        Goods goods = null;
        //判断有没有库存
//        for (int i = 0; i < goodslist.size(); i++) {}  优化后为：
        for (int i = 0,length = goodslist.size(); i < length; i++) {
            Object element = goodslist.getElement(i);
            if (element instanceof Goods goods1) {
                if (goods1.getGoodsNo().equals(no)){
                    goods = goods1;
                }
            }
        }
        if (goods == null) {
            //新入库
            goods = new Goods();
            goods.setGoodsNo(no);

            print("请输入商品名称：");
            String goodsName = INPUT.next();
            goods.setGoodsName(goodsName);

            print("请输入商品进价：");
            double cost = INPUT.nextDouble();
            goods.setCost(cost);

            print("请输入商品售价：");
            double price = INPUT.nextDouble();
            goods.setPrice(price);

            showCategory();  //展示商品分类列表
            print("选择商品分类：");
            int category = INPUT.nextInt();
            for (int i = 0; i < categoryList.size(); i++) {
                Object element = categoryList.getElement(i);
                if (element instanceof Category category1) {
                    if (category1.getNo() == category) {
                        goods.setCategory(category1);
                        break;
                    }
                }
            }

        }
            print("请输入商品数量：");
            int count = INPUT.nextInt();
            goods.setCount(goods.getCount() + count);

            goodslist.add(goods);
            println("添加商品成功 ！");
            adminMenuList();

    }

    /**
     * 展示商品分类列表
     */
    private void showCategory() {
        String categorys = categoryList.toString();
        println("现有商品分类如下：");
        if ("".equals(categorys)){
            println("暂无商品分类");
        }else {
            println(categorys);
        }
        println("请选择你要进行的操作：");
        adminMenuList();
    }

    /**
     * 检查账号是否正确
     */
    public Account checkAccount(Account account ,MyList list){
        for (int i = 0; i < list.size(); i++) {
            Object element = list.getElement(i);
            if (element instanceof Account account1){
                if (account.login(account1)){
                    return account1;
                }
            }
        }
        return null;
    }


    /**
     * 注册
     */
    private void register(){
        println("注册：根据提示输入会员信息");
        print("请输入手机号:");
        String phone = INPUT.next();
        //校验该手机号是否已注册
        for (int i = 0; i < vipList.size(); i++) {
            Object element = vipList.getElement(i);
            if (element instanceof Vip vip) {
                phone.equals(vip.getPhone());
                    if (phone.equals(vip.getPhone())){
                        println("该手机号已被注册");
                        register();
                    }
            }

        }
        String password = null;
        do {
            print("请输入密码:");
            password = INPUT.next();
            print("请再次输入密码:");
            String password1 = INPUT.next();
            if (!password.equals(password1)){
                println("两次密码输入不一致，请重新输入！");
            }else {
                break;
            }
        } while (true);
        print("请输入会员姓名:");
        String name = INPUT.next();

        //保存会员信息
        Vip vip = new Vip(phone,password,name);
        addVip(vip);

        println(name + ",恭喜您称为本店的会员！");

        //返回上一级
        indexMenuList();
    }

    /**
     * 添加会员信息
     */
    public static boolean addVip(Vip vip){
        return vipList.add(vip);
    }

    /**
     * 管理员登录
     */
    private void loginAdmin() {
        print("请输入手机号:");
        String phone = INPUT.next();
        print("请输入密码:");
        String password = INPUT.next();
        Admin login = new Admin(phone,password,null);
        Account flag = checkAccount(login,adminList);
        if (flag instanceof Admin admin){
            login = admin;
        }
        if (flag != null){
            currentUser = login;
            println(login.getName() + ",欢迎您！");
            adminMenuList();
        }else {
            println("账号和密码错误，请重试！");
            indexMenuList();
        }
    }

    /**
     * 管理员功能提示
     */
    private void adminMenuList() {
        println("1.会员信息");
        println("2.商品入库");
        println("3.是否新增商品分类");
        println("4.现有商品分类");
        println("5.商品列表");
        println("0.退出");
        print("请选择：");
        int in = INPUT.nextInt();
        //如果in=0,0+0=0，就退出，如果in不等于0，就在in的基础上加200，成为新的管理员路由，200是一个基准
        in = in + (in == 0 ? 0 : 200);
//        if (in != 0) {
//            in += 200;
//        }
        router(in);
    }

    /**
     * 登录
     */
    private void login(){
        print("请输入手机号:");
        String phone = INPUT.next();
        print("请输入密码:");
        String password = INPUT.next();
        Vip login = new Vip(phone,password,null);
        Account flag = checkAccount(login,vipList);
        if (flag instanceof Vip vip){
            login = vip;
        }
        if (flag != null){
            currentUser = login;
            currentUser.setShopCar(new MyList(1));
            println(login.getName() + ", 欢迎您！");
            shopping();
            //结账
            pay();
        }else {
            println("账号或密码错误，请重试!");
            indexMenuList();
        }
    }

    private void pay() {
        println("您本次的购买清单是:");
        MyList shopCar = currentUser.getShopCar();
        println("序号\t商品名称\t单价\t数量\t小计");
        double sum = 0;
        for (int i = 0; i < shopCar.size(); i++) {
            Treasure element = (Treasure) shopCar.getElement(i);
            sum += element.getSum();
            println( (i + 1) + "\t" + element);
        }
        println("总计:" + sum + "元");
        double in = sum;
        if (currentUser instanceof Vip vip) {
            Level level = vip.getLevel();
            in = level.getDiscount() * sum;
            double money = 0.0;
            do {
                print("收款：");
                money = INPUT.nextDouble();
                if (money < in) {
                    print("付款金额不足，请重新支付");
                }else {
                    break;
                }
            } while (true);

            println("找零：" + (money - in));

            //修改商品库存
            for (int i = 0; i < shopCar.size(); i++) {
                Treasure element = (Treasure) shopCar.getElement(i);

                Goods goods = element.getGoods();
                goods.setCount(goods.getCount() - element.getNum());
            }
            //积分
            int point = (int) Math.floor(in);
            vip.setPoint(vip.getPoint() + point);

            //能否升级会员
            for (int i = levelList.size() - 1; i >= 0; i--) {
                Level element = (Level) levelList.getElement(i);
                if (element.getBase() < vip.getPoint()) {
                    //符合当前等级
                    if (!element.getName().equals(vip.getLevel().getName())) {
                        vip.setLevel(element);
                        println("恭喜您，升级为本店的【" + element.getName() + "】，以后可享" + (int)(element.getDiscount()*10) + "折。" );
                        break;
                    }
                    break;
                }

            }
        }
        logout();
    }

    private void logout() {
        println("欢迎下次再来！");
        currentUser = null;
        indexMenuList();
    }

    private void shopping() {
        showGoodsList();
        print("请输入要购买的商品:");

        String no = INPUT.next();
        int index = goodslist.search(new Goods(no));
        Goods goods = (Goods) goodslist.getElement(index);

        print("请输入购买 【" + goods.getGoodsName() + "】的数量：");
        int count = INPUT.nextInt();
        while (goods.getCount() < count) {
            println("亲亲，小店商品不够了奥，请重新输入购买的数量：");
            count = INPUT.nextInt();
        }
        currentUser.getShopCar().add(new Treasure(goods,count));

        print("是否继续购物？ 1.继续购买   2.结账");
        int t = INPUT.nextInt();
        if (t==1) {
            shopping();
        }
        return;
    }

    /*
    private void login() {
        println("请输入您的账号（手机号）");
        String phone = INPUT.next();
        println("请输入密码");
        String password = INPUT.next();
        for (int i = 0; i < vipList.size(); i++) {
            Object element = vipList.getElement(i);
            if (element instanceof Vip vip) {
//                phone.equals(vip.getPhone());
                if (phone.equals(vip.getPhone())) {
//                    password.equals(vip.getPassword());
                    if (password.equals(vip.getPassword())){
                        println("登录成功！");
                        break;
                    }else {
                        println("密码错误，请重新输入");
                        login();
                    }
                }else {
                    println("账号不存在");
                    indexMenuList();
                }
            }
        }
    }
    */

    /**
     * 显示所有会员信息
     */
    private void showVipList(){
        println("现在共有" + vipList.size() + "名会员，信息如下:");
        println(vipList.toString());
        adminMenuList();
//        indexMenuList();
    }

    /**
     * 退出
     */
    private void exit(){
        println("欢迎下次光临！");
    }

    /**
     * 控制台打印封装
     * @param  str 打印内容
     */
    public static void println(String str){
        System.out.println(str);
    }
    public static void print(String str){
        System.out.println(str);
    }

}
